<?php

    //PHP stdClass Object转array
    function toArray($array) {
        if(is_object($array)) {
            $array = (array)$array;
        } if(is_array($array)) {
            foreach($array as $key=>$value) {
                $array[$key] = toArray($value);
            }
        }
        return $array;
    }

 /**
 * @param $start string 第一个参数
 * @param $end   string 第二个参数
 * @return array|string 时间数组|错误字符串
 */
function dateDiff($start,$end){
    $time = ['start'=>$start,'end'=>$end];
    //判断是否为时间格式或时间戳,若是统一转成时间戳,否则退出
    foreach ($time as &$v){
        if(strtotime($v) || strtotime(date("Y-m-d H:i:s",(int)$v)) == $v){
            if(strtotime($v)){
                $v = strtotime($v);
            }
        }else{
            return '时间格式有误';
        }
    }
    if($time['start'] - $time['end'] > 0){
        $max = $time['start'];
        $min = $time['end'];
    }else{
        $max = $time['end'];
        $min = $time['start'];
    }
    //相差总时间戳
    $diff = $max - $min;
    //相差天数
    $day = intval($diff / (60*60*24)); //60*60*24一天时间
    //相差小时数
    $hour = intval(($diff%(60*60*24))/(60*60)); //求余除天数外的时间戳并除以一小时
    //相差分钟数
    $mins = intval(($diff%(60*60*24))%(60*60)/60);
    //相差秒数
    $secs = intval(($diff%(60*60*24))%(60*60)%60);
    $time['diff'] = $diff;
    $time['day'] = $day;
    $time['hour'] = $hour;
    $time['min'] = $mins;
    $time['secs'] = $secs;
    return $time;
}

/**
 * 利用php自带函数计算
 * @param $start string 第一个参数
 * @param $end   string 第二个参数
 * @return array|string 时间数组|错误字符串
 */
function dateDiff($start,$end){
    $data = ['start'=>$start,'end'=>$end];
    //判断是否为时间格式或时间戳,统一转为时间格式
    foreach ($data as &$v){
        if(strtotime($v) || strtotime(date("Y-m-d H:i:s",(int)$v)) == $v){
            if(!strtotime($v)){
                $v = date("Y-m-d H:i:s",$v);
            }
        }else{
            return '时间格式有误';
        }
    }
    $datetime1 = new DateTime($data['start']);
    $datetime2 = new DateTime($data['end']);
    $interval = $datetime1->diff($datetime2);
    //相差总天数
    $data['day'] = $interval->format('%a');
    //相差小时
    $data['hour'] = $interval->format('%h');
    //相差分钟数
    $data['min'] = $interval->format('%i');
    //相差秒数
    $data['sec'] = $interval->format('%s');
    return $data;
}